package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Override
    public R<Employee> login(Employee employee) {
        //1. 根据提交的用户名username查询数据库中员工数据信息
        Employee dbEmployee = employeeMapper.login(employee);
        //查询结果,则返回登录失败结果
        if (dbEmployee == null) {
            return R.error("用户不存在");
        }
        //对比密码
        final String md5Password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if (!md5Password.equals(dbEmployee.getPassword())) {
            return R.error("密码错误");
        }
        if (dbEmployee.getStatus() == 0) {
            return R.error("账号被禁用");

        }
        //登录成功
        return R.success(dbEmployee);
    }

    @Override
    public void save(Employee employee) {
        //对密码进行加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());
        employeeMapper.save(employee);
    }

    /**
     * 员工分页
     *
     * @param page     当前页
     * @param pageSize 页面大小
     * @param name     用户名
     * @return
     */
    @Override
    public Page<Employee>findByPage(int page, int pageSize, String name) {
        //1. 设置开始页与页面大小
        PageHelper.startPage(page, pageSize);
        //2. 查询页面的数据
        List<Employee> employeeList = employeeMapper.findByName(name);
        //3. 创建PageInfo对象
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);
        //4. 转换为Page对象
      Page<Employee> pageResult = new Page<>(pageInfo.getList(), pageInfo.getTotal(),pageInfo.getSize(),pageInfo.getPageNum());
        return pageResult;
    }

    /**
     * 更新员工信息
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }

    /**
     * 根据id查找员工
     *
     * @param id
     * @return
     */
    @Override
    public R<Employee> findById(long id) {
       Employee employee= employeeMapper.finById(id);
       return R.success(employee);
    }
}
